﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Role;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.Role
{
    public class DelRoleHandler : IRequestHandler<DelRoleCommon, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public DelRoleHandler(IBaseRepository<RoleModel> roleRepo,IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(DelRoleCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            //var rolename = roleRepo.GetAll().Where(x=>x.RoleName==request.RoleName).FirstOrDefault();
            //if (rolename != null)
            //{
            //    res.Code=ApiEnum.Success;
            //    res.Message = "角色名称已存在";
            //    return Task.FromResult(res);
            //}

            var roleinfo= roleRepo.GetValue(request.RoleId).Result;

            roleinfo.IsDeleted = true;

            var r = 0;
            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r= roleRepo.Update(roleinfo).Result;
                tran.Complete();
            }
            if(r>0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "删除成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "删除失败";
                return Task.FromResult(res);
            }
                

                    



        }
    }
}
